from lib import log

import WorldObject
import Player

class Location(WorldObject.WorldObject):
    def __init__(self, name, description, world):
        super(Location, self).__init__(world)
        self._name = name
        self._description = description
        self._objectsAtLocation = list()
        self._playersAtLocation = list()
        
    @property
    def name(self): return self._name
    @property
    def description(self): return self._description
    @property
    def objectsAtLocation(self): return self._objectsAtLocation
    @property
    def playersAtLocation(self): return self._playersAtLocation
    
    def player_look(self, player, fullCommand):
        player.message("You see: {0}".format(self.name))
        if "carefully" in fullCommand:
            player.message(self.description) 
        if len(self._objectsAtLocation) > 0:
            player.message("You also see the following items:")
            self.listObjects(player)
        if len(self._playersAtLocation) > 0:            
            player.message("You also see the following players:")
            self.listPlayers(player)
    
    def listObjects(self, player):
        for obj in self._objectsAtLocation:
            player.message("  {0}".format(obj.name))
    
    def listPlayers(self, player):
        for obj in self._playersAtLocation:
            player.message("  {0}".format(obj.playerId))
    
    def objectLeft(self, obj, toLocation):
        if obj.isPlayer:
            if obj in self._playersAtLocation:
                self._playersAtLocation.remove(obj)
            else:
                log.warn("{0} apparently left {1} -- no record of this player".format(obj.name, self.name))
        elif obj.isThing and obj in self._objectsAtLocation:
            self._objectsAtLocation.remove(obj)
    
    def objectEntered(self, obj, fromLocation):
        if obj.isPlayer:
            self._playersAtLocation.append(obj)
        elif obj.isThing:
            self._objectsAtLocation.append(obj)
    
    def hasCommand(self, command):
        return hasattr(self, "player_" + command)
    
    def executeCommand(self, player, command, modifiers):
        command_func = getattr(self, "player_" + command)
        command_func(player, modifiers)
    
    def broadcast(self, message):
        """
        Tells each player currently in the room a message
        """
        for player in self._playersAtLocation:
            player.message(message)
    